package com.example.demo.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.demo.config.ApplicationContextAwareConfig;
import com.example.demo.entity.User;
import com.example.demo.entity.UserCopy;
import com.example.demo.mapper.user.UserCopyMapper;
import com.example.demo.mapper.user.UserDao;
import com.example.demo.service.aplication.UserCopyService;
import com.example.demo.service.UserService;
import com.example.demo.service.aplication.UserCopyServiceOneImpl;
import com.example.demo.util.AsyncUtils;
import com.example.demo.util.EmptyUtil;
import com.example.demo.vo.print.Detail;
import com.example.demo.vo.print.Print;
import com.example.demo.vo.print.PrintParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("userService")
public class UserServiceImpl implements UserService {

    Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AsyncUtils asyncUtils;

    @Autowired
    private UserCopyMapper userCopyMapper;

    /** 通过指定名称限定service */
    @Resource(name="userCopyServiceTwoImpl")
    private UserCopyService copy1;



    @Override
    public List<User> getUserList() {
        //通过指定名称限定service
        copy1.getUserList();
        //通过apolicationContext获取指定service
        UserCopyService copy2 = ApplicationContextAwareConfig.getBean(UserCopyServiceOneImpl.class);
        copy2.getUserList();

        UserCopy userCopy = userCopyMapper.selectByPrimaryKey(1L);
        logger.info(userCopy.toString());
        //执行异步方法
        asyncUtils.getAsync();
        return userDao.getUserList();
    }

    @Override
    public User queryUser(User user) {
        //执行异步方法
        asyncUtils.getAsync();
        return userDao.queryUser(user);
    }

    @Override
    public User queryUserById(Integer id) {
        User u = null;
        //拼接redis 中的key
        String userId = "userId_" + id;
        ValueOperations<String,User> operations = redisTemplate.opsForValue();
        //判断redis中是否包含key
        if(redisTemplate.hasKey(userId)){
            System.out.println("从redis中获取用户信息...................");
            u = operations.get(userId);
            if(!EmptyUtil.isEmpty(u)){
                return u;
            }
        }
        System.out.println("从数据库中获取用户信息..................");
        u = new User();
        u.setId(id);
        u = userDao.queryUser(u);
        if(!EmptyUtil.isEmpty(u)){
            System.out.println("更新redis用户信息，key = userId_" + u.getId());
            //更新redis中用户信息，过期时间为1小时
            operations.set(userId,u, 100,TimeUnit.HOURS);
        }
        return u;
    }

    @Override
    public void addUser(User user) {
        userDao.addUser(user);
    }

    @Override
    public void updateUser(User user) {
        userDao.updateUser(user);
    }

    @Override
    public String printTest() {
        String value = "{\n" +
                "    \"Host\":\"127.0.0.1\",\n" +
                "    \"PrintParams\":[\n" +
                "    {\n" +
                "        \"TemplateId\":\"123456\",\n" +
                "        \"Details\":[\n" +
                "            {\n" +
                "                \"Key\":\"QTY\",\n" +
                "                \"Value\":\"999\"\n" +
                "            },{\n" +
                "                \"Key\":\"QTY\",\n" +
                "                \"Value\":\"999\"\n" +
                "            }\n" +
                "        ]\n" +
                "    }\n" +
                "]\n" +
                "}";



        /*


        Print print = new Print();
        print.setHost("10.245.228.180");

        PrintParam printParam = new PrintParam();
        printParam.setTemplateId("L5 PN.lab");
        //printParam.setQty(5);

        List<Detail> details = new ArrayList<>();
        Detail detail1 = new Detail();
        detail1.setKey("V_SN");
        detail1.setValue("88888888888888888888");
        details.add(detail1);
        Detail detail2 = new Detail();
        detail2.setKey("V_IPN");
        detail2.setValue("99999999999999999999");
        details.add(detail2);

        printParam.setDetails(details);

        List<PrintParam> printParams = new ArrayList<>();
        printParams.add(printParam);

        print.setPrintParams(printParams);

        JSONObject.toJSONString(print);

        String jsonString = JSON.toJSONString(print, SerializerFeature.WriteSlashAsSpecial);*/



        JSONObject object = new JSONObject();
        object.put("host", "10.245.228.180");

        JSONObject printParam = new JSONObject();
        printParam.put("templateId", "L5 PN.lab");
        Map<String, Object> detail = new HashMap<>();
        detail.put("key", "V_SN");
        detail.put("value", "88888888888888888888");
        JSONArray details = new JSONArray();
        details.add(detail);
        detail = new HashMap<>();
        detail.put("key", "V_IPN");
        detail.put("value", "99999999999999999999");
        details.add(detail);
        //details.add(detail);
        printParam.put("details", details);

        JSONArray printParams = new JSONArray();
        printParams.add(printParam);

        object.put("printParams", printParams);
        //log.info("打印参数：{}", object.toJSONString());

        //stringRedisTemplate.convertAndSend("CodeSoftChannel", object.toJSONString());

        redisTemplate.convertAndSend("CodeSoftChannel",object.toJSONString());
        //redisTemplate.opsForValue().set("gogogo", jsonString);
        //redisTemplate.convertAndSend("CodeSoftChannel",JSONObject.toJSONString(print));
        return "ok";
    }
}
